package wnhz.com.business;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.MainActivity;
import wnhz.com.business.groupshop.bean.IndustryBean;
import wnhz.com.business.groupshop.bean.InfoBean;
import wnhz.com.business.groupshop.bean.JobBean;
import wnhz.com.business.groupshop.ui.MeassageChangeActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.shareshop.ShareShopActivity;
import wnhz.com.business.shareshop.activity.mine.AllOrderActivity;
import wnhz.com.business.shareshop.bean.CompleteInfoBean;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.ImageLoaderUtil;
import wnhz.com.business.uitls.MyBitmapUtils;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.imgselect.BitnapUtils;
import wnhz.com.business.uitls.imgselect.GlideImageLoader;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.TranslucentActionBar;

import static com.umeng.socialize.utils.ContextUtil.getContext;

/**
 * Created by lizhenglong on 2017-10-25 0025.
 * 完善信息
 */

public class CompleteInfoActivity extends MyBaseActivity implements View.OnClickListener, ActionBarClickListener {
    private static final int IMAGE_PICKERS = 100;

    @BindView(R.id.actionBar)
    TranslucentActionBar actionBar;
    @BindView(R.id.img_complete_head)//头像
            CircleImageView img_complete_head;
    @BindView(R.id.ll_touxiang)//头像
            LinearLayout ll_touxiang;
    @BindView(R.id.et_nickname)//昵称
            EditText et_nickname;
    @BindView(R.id.tv_industry)//行业方向
            TextView tv_industry;
    @BindView(R.id.tv_chose_birth)//生日
            TextView tv_chose_birth;
    @BindView(R.id.tv_chose_job)//职业
            TextView tv_chose_job;

    @BindView(R.id.sex_man)//性别男
            RadioButton sex_man;
    @BindView(R.id.sex_woman)//性别女
            RadioButton sex_woman;
    @BindView(R.id.sex_chose)//性别选择
            RadioGroup sex_chose;
    @BindView(R.id.btn_complete_next)
    Button btnCompleteNext;

    private String completetype;//1从注册界面  2从个人中心界面进入
    private List<IndustryBean.InfoBean> industryList = new ArrayList<>();//行业列表
    private String industryid = "";//行业id
    private List<JobBean.InfoBean> joblist = new ArrayList<>();//职业列表
    private String jobid = "";
    private String birthday = "";
    private String sex = "1";

    private File output;
    private Uri imageUri;
    private Bitmap bm = null;
    private PopupWindow popup;
    private final int TAKE_PHOTO = 1;
    private final int CHOOSE_PHOTO = 2;
    private TextView tv_takepoto, tv_choosephoto, tv_cancel, empty_takepic;

    private String testpath = "";
    private ImagePicker imagePicker;

    public static Intent createIntent(Context context, String completetype) {
        Intent intent = new Intent(context, CompleteInfoActivity.class);
        intent.putExtra("completetype", completetype);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_completeinfo);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionBar.setStatusBarHeight(getStatusBarHeight());
        }
        completetype = getIntent().getStringExtra("completetype");
        if("1".equals(completetype)){  //默认为View.GONE  个人中心进来completetype 2
            actionBar.setData("填写个人信息", R.drawable.ic_lefft_white, null, 0, "跳过", 0, this);
        }else if("2".equals(completetype)){
            actionBar.setData("信息修改", R.drawable.ic_lefft_white, null, 0, "", 0, this);
            loadData();
        }

        makeflie();
        sex_chose.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == sex_man.getId()) {//选择性别男
                    sex = "1";
                } else if (checkedId == sex_woman.getId()) {//选择性别女
                    sex = "2";
                }
            }
        });
        initImgSelect();
    }

    private void loadData() {
        Map<String,String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token",MyApplication.getInstance().getInfoBean().getToken());
        OkGo.<String>post(Url.UCENTER_INFO)
                .tag(this)
                .params(map,false)
                .execute(new DialogCallback<String>(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("共享商城个人中心修改信息", response.body().toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().toString());
                            String re = jsonObject.optString("re");
                            if (re.equals("1")){
                                Gson gson = new Gson();
                                CompleteInfoBean meassageChangeBean = gson.fromJson(response.body().toString(), CompleteInfoBean.class);
                                et_nickname.setText(meassageChangeBean.getInfo().getUsername() == null ? "" : meassageChangeBean.getInfo().getUsername());//昵称
                                if(!TextUtils.isEmpty(meassageChangeBean.getInfo().getHead_img())){
                                    ImageLoaderUtil.displayImage(getContext(),img_complete_head,meassageChangeBean.getInfo().getHead_img(),null);//头像
                                }
//                                tv_industry.setText(); //行业
                                if("1".equals(meassageChangeBean.getInfo().getSex())){ //性别
                                    sex = "1";
                                    sex_man.setChecked(true);
                                    sex_woman.setChecked(false);
                                }else if("2".equals(meassageChangeBean.getInfo().getSex())){
                                    sex = "2";
                                    sex_man.setChecked(false);
                                    sex_woman.setChecked(true);
                                }
                                tv_chose_birth.setText(meassageChangeBean.getInfo().getBirth() == null ? "" : meassageChangeBean.getInfo().getBirth()); //生日
//                                tv_chose_job.setText(); //职业
                            }else {
                                ToastUtils.showToast(CompleteInfoActivity.this,"获取信息失败");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("共享商城个人中心onError","------------");
                    }
                });
    }

    private void initImgSelect() {
        imagePicker = ImagePicker.getInstance();

        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器

        imagePicker.setShowCamera(true);  //显示拍照按钮

        imagePicker.setCrop(true);        //允许裁剪（单选才有效）

//        imagePicker.setSaveRectangle(true); //是否按矩形区域保存

        imagePicker.setSelectLimit(1);    //选中数量限制

//        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状

        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）

        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素

        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }
    @Override
    protected void handleMsg(Message msg) {

    }

    @OnClick({ R.id.rl_chose_industry, R.id.rl_chose_job, R.id.rl_chose_birth, R.id.ll_touxiang,
    R.id.btn_complete_next})
    void Click(View v) {
        switch (v.getId()) {
            case R.id.rl_chose_industry://选择行业
                choseIndustry();
                break;
            case R.id.rl_chose_job://选择职业
                choseJob();
                break;
            case R.id.rl_chose_birth:
                new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        birthday = format.format(date);
                        tv_chose_birth.setText(format.format(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setSubmitColor(Color.RED)//确定按钮文字颜色
                        .setCancelColor(Color.RED)//取消按钮文字颜色
                        .build().show();
                break;
            case R.id.ll_touxiang://选择头像
//                seepop();
                Intent intents = new Intent(CompleteInfoActivity.this, ImageGridActivity.class);
                startActivityForResult(intents, IMAGE_PICKERS);
                break;
            case R.id.btn_complete_next:
                if (TextUtils.isEmpty(et_nickname.getText().toString())){
                    MyToast("昵称不能为空");
                    return;
                }
                if (TextUtils.isEmpty(tv_industry.getText().toString())){
                    MyToast("请选择行业");
                    return;
                }
                if (TextUtils.isEmpty(tv_chose_birth.getText().toString())){
                    MyToast("请选择出生日期");
                    return;
                }
                if (TextUtils.isEmpty(tv_chose_job.getText().toString())){
                    MyToast("请选择职业");
                    return;
                }
                if (TextUtils.isEmpty(testpath)){
                    MyToast("请选择头像");
                    return;
                }
                Intent intent = new Intent(CompleteInfoActivity.this,LableActivity.class);
                intent.putExtra("type",2);
                intent.putExtra("sex", sex);// 性别  1男  2女
                intent.putExtra("username", et_nickname.getText().toString());
                intent.putExtra("head_img", testpath);
                intent.putExtra("birth", tv_chose_birth.getText().toString());
                intent.putExtra("industry_id", industryid);
                intent.putExtra("job_id", jobid);
                startActivity(intent);
                break;
        }
    }

    /**
     * 选择职业
     */
    private void choseJob() {
        Map<String, String> map = new HashMap<>();
        SharedPreferences sp = getSharedPreferences("userinfo", 0);
        final String token = sp.getString("token", "0");
        if ("0".equals(token)) {
            MyToast("获取信息失败");
            return;
        } else {
            map.put("token", token);
            map.put("type", "3");//1-标签  2-行业方向  3-职位
            OkGo.<String>post(Url.UCENTRER_GETLABELLIST)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(this) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("选择职业onSuccess", response.body().toString());
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String re = jsonObject.optString("re");
                            if (re.equals("1")) {
                                Gson gson = new Gson();
                                JobBean jobBean = gson.fromJson(response.body(), JobBean.class);
                                joblist = jobBean.getInfo();
                                showJobPickciew();
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    /**
     * 职业选择器
     */
    private void showJobPickciew() {
        if (joblist.size() == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < joblist.size(); i++) {
            list.add(joblist.get(i).getName());
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                jobid = joblist.get(options1).getJob_id();
                tv_chose_job.setText(joblist.get(options1).getName());
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.red2552))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.red2552))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }

    /**
     * 选择行业
     */
    private void choseIndustry() {
        Map<String, String> map = new HashMap<>();
        SharedPreferences sp = getSharedPreferences("userinfo", 0);
        final String token = sp.getString("token", "0");
        if ("0".equals(token)) {
            MyToast("获取信息失败");
            return;
        } else {
            map.put("token", token);
            map.put("type", "2");//1-标签  2-行业方向  3-职位
            OkGo.<String>post(Url.UCENTRER_GETLABELLIST)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<String>(this) {
                        @Override
                        public void onSuccess(Response<String> response) {
                            Log.e("选择行业onSuccess", response.body().toString());
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String re = jsonObject.optString("re");
                            if (re.equals("1")) {
                                Gson gson = new Gson();
                                IndustryBean industryBean = gson.fromJson(response.body(), IndustryBean.class);
                                industryList = industryBean.getInfo();
                                showIndustryPickciew();
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    /**
     * 行业选择器
     */
    private void showIndustryPickciew() {
        if (industryList.size() == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < industryList.size(); i++) {
            list.add(industryList.get(i).getName());
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                industryid = industryList.get(options1).getIndustry_id();
                tv_industry.setText(industryList.get(options1).getName());
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.red2552))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.red2552))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }

    /**
     * 登录
     */
    private void login() {
        Map<String, String> map = new HashMap<>();
        SharedPreferences sp = getSharedPreferences("userinfo", 0);
        final String phone = sp.getString("username", "0");
        final String password = sp.getString("password", "0");
        if ("0".equals(phone) && "0".equals(password)) {
//            MyApplication.getInstance().BackLoginActivity();
            return;
        } else {
            map.put("mobile", Base64Util.encodedString2(phone));
            map.put("password", Base64Util.encodedString2(password));
            map.put("type", "1");
            OkGo.<InfoBean>post(Url.USER_LOGIN)
                    .tag(this)
                    .params(map, false)
                    .execute(new DialogCallback<InfoBean>(this) {
                        @Override
                        public void onSuccess(Response<InfoBean> response) {
                            if (response.body().getRe().equals("1")) {
                                Log.e("登录onSuccess", "" + response.body().getInfo());
                                SharedPreferences sp = getSharedPreferences("userinfo", 0);
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putString("username", phone);
                                editor.putString("password", password);
                                editor.putString("token", response.body().getToken());
                                editor.putString("logintype", "1");
                                editor.commit();
                                InfoBean infoBean = new InfoBean();
                                infoBean.setToken(response.body().getToken());
                                infoBean.setLogintype("2");
                                MyApplication.getInstance().setInfoBean(infoBean);
                                Intent intent = new Intent(CompleteInfoActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                MyToast(response.body().getInfo());
                            }
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                        }

                        @Override
                        public void onError(Response<InfoBean> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    private void makeflie() {
        /**
         * 最后一个参数是文件夹的名称，可以随便起
         */
        String path = Environment.getExternalStorageDirectory().toString() + "/SYB";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        /**
         * 这里将时间作为不同照片的名称
         */
        output = new File(file, System.currentTimeMillis() + ".jpg");

        /**
         * 如果该文件夹已经存在，则删除它，否则创建一个
         */
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void seepop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.item_takephoto, null);
        popup = new PopupWindow(contentView);
        popup.setOutsideTouchable(true);
        popup.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        tv_takepoto = (TextView) contentView.findViewById(R.id.tv_takepoto);
        tv_choosephoto = (TextView) contentView.findViewById(R.id.tv_choosepoto);
        tv_cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        empty_takepic = (TextView) contentView.findViewById(R.id.empty_takepic);
        tv_takepoto.setOnClickListener(this);
        tv_choosephoto.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        empty_takepic.setOnClickListener(this);
    }

    /**
     * 头像选择
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //拍照
            case R.id.tv_takepoto:

                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA}, 3);

                } else {
                    imageUri = Uri.fromFile(output);
                    Intent intents = new Intent("android.media.action.IMAGE_CAPTURE");
                    intents.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intents, TAKE_PHOTO);
                    popup.dismiss();
                }

                break;
            //选择相册
            case R.id.tv_choosepoto:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");//相片类型
                startActivityForResult(intent, CHOOSE_PHOTO);
                popup.dismiss();
                break;
            //取消
            case R.id.tv_cancel:
                popup.dismiss();
                break;
            case R.id.empty_takepic:
                popup.dismiss();
                break;
        }
    }

    private static final String compressImageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/esl/Compress/"; // 图片及其他数据保存文件夹
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {

            if (data != null) {
                switch (requestCode) {
                    case IMAGE_PICKERS:
                        ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        for (int i = 0; i < images.size(); i++) {
                            testpath = BitnapUtils.compressImage(images.get(i).path, compressImageFilePath + System.currentTimeMillis() + ".jpg", 40);
                            Glide.with(CompleteInfoActivity.this).load(testpath).into(img_complete_head);
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        startActivity(new Intent(this, ShareShopActivity.class));
        finish();
    }

    @Override
    public void onEditTextClick() {

    }
}
